<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Column as Columns;
use think\Db;

/**
 * @圈子接口
 */
class Column extends Api
{    
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list', 'info', 'listRecommend'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * @圈子列表
     */
    public function list(Columns $D)
    {
        $categories = $D->All();
        $tree = buildTree($categories);
        
        $this->success('圈子列表', $tree);
    }
    
    
    /**
     * @我加入的圈子列表
     */
    public function listJoin(Columns $D)
    {
        $user = $this->auth->getUserinfo();
        $categories = $D->where('id', 'in', $user['column_join'])->select();
        
        $this->success('我加入的圈子列表', $categories);
    }
    
    
    /**
     * @我管理的圈子列表
     */
    public function listManage(Columns $D)
    {
        $user = $this->auth->getUserinfo();
        $categories = $D->where('id', 'in', $user['column_manage'])->select();
        
        $this->success('我管理的圈子列表', $categories);
    }

    
    /**
     * @推荐圈子
     */
    public function listRecommend(Columns $D, $limit = 8, $flag = 'top') {
        $map['pid'] = ['gt', 0];
        $map[] = ['exp',Db::raw("FIND_IN_SET('{$flag}',flag)")];
        $list = $D->where($map)->limit($limit)->select();
        $arr = ['top' => '置顶圈子', 'hot' => '热门圈子'];
        
        $this->success($arr[$flag].'列表', $list);
    }    
    
    /**
     * @圈子详情
     */
    public function info(Columns $D, $column_id = null)
    {
        if (!$column_id) {
            $this->error('圈子id不能为空');
        }
        $info = $D->get($column_id);
        
        $this->success('圈子详情', $info);
    }
    
    
    /**
     * @加入圈子
     */
    public function join($column_id = null) {
        if (!$column_id) {
            $this->error('圈子id不能为空');
        };
        $user = $this->auth->getUserinfo();
        if ($user['column_join']) {
            if (in_array($column_id, explode(',', $user['column_join']))) {
                $this->error('该圈子您已加入，勿须重复！');
            }
            db('user')->where('id', $user['id'])->setField('column_join',  $user['column_join'].','.$column_id);
        } else {
            db('user')->where('id', $user['id'])->setField('column_join',  $column_id);
        }
        
        $this->success('加入圈子成功');
    }
    
    
    /**
     * @退出圈子
     */
    public function quit($column_id = null) {
        $user = $this->auth->getUserinfo();
        $arrColumn = explode(',', $user['column_join']);
        if (!in_array($column_id, $arrColumn)) {
            $this->error('该圈子您还没加入');
        }
        $arrColumn = array_diff($arrColumn, [$column_id]);
        
        if (db('user')->where('id', $user['id'])->setField('column_join',  implode(',', $arrColumn))) {
            $this->success('取消关注成功');
        }
        
        $this->error('服务器繁忙，请稍后再试');
    } 
    
}
